package com.atguigu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @title：
 * @author：Yu
 * @create：2023-03-05 16:01
 * @description：
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth
//                .inMemoryAuthentication()
//                .withUser("admin")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("");
//    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置frame显示问题
        http.headers().frameOptions().disable();
        //设置放行资源
        http.authorizeRequests().antMatchers("/login", "/static/**").permitAll().anyRequest().authenticated();
        //设置登录资源，以及登陆后跳转的地址
        http.formLogin().loginPage("/login").defaultSuccessUrl("/index.html");
        //退出登录
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login");
        //关闭跨域
        http.csrf().disable();
        //设置没有权限时跳转的页面,一旦没有权限就会跳转到CustomAccessDeineHandler类下执行handler方法
        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeineHandler());
        //记住我，如果使用框架页面则不用加rememberMeParameter("remember")，如果使用自定义页面需要加上参数为前台的传过来的name
        http.rememberMe().rememberMeParameter("remember");
    }
}
